{{ template "page/head_start" .}}
<style>
  body {
    background-color: #f5f7fa;
  }

  .settings-card {
    background: white;
    border-radius: 10px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 1.5rem;
  }

  .save-bar {
    position: sticky;
    top: 0;
    z-index: 100;
    background: white;
    padding: 1rem 0;
    margin-bottom: 1.5rem;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
  }

  .nav-tabs {
    border-bottom: 2px solid #dee2e6;
  }

  .nav-tabs .nav-link {
    color: #6c757d;
    font-weight: 600;
    border: none;
    border-bottom: 3px solid transparent;
    padding: 1rem 1.5rem;
    transition: all 0.3s ease;
  }

  .nav-tabs .nav-link:hover {
    color: #667eea;
    background: rgba(102, 126, 234, 0.05);
  }

  .nav-tabs .nav-link.active {
    color: #667eea;
    background: transparent;
    border-bottom-color: #667eea;
  }

  .accordion-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: 600;
  }

  .accordion-button:not(.collapsed) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: none;
  }

  .accordion-button::after {
    filter: brightness(0) invert(1);
  }

  .accordion-button:focus {
    box-shadow: none;
    border-color: rgba(102, 126, 234, 0.5);
  }

  .setting-item {
    padding: 1.25rem 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .setting-item:last-child {
    border-bottom: none;
  }

  .setting-label {
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 0.25rem;
  }

  .setting-description {
    font-size: 0.875rem;
    color: #7f8c8d;
    margin-bottom: 0.75rem;
  }

  .alert-security {
    background: linear-gradient(135deg, #ff9100 0%, #ff5722 100%);
    color: white;
    border: none;
    border-radius: 10px;
    animation: pulse-warning 3s ease-in-out infinite;
  }

  @keyframes pulse-warning {
    0%, 100% {
      box-shadow: 0 0 0 0 rgba(255, 145, 0, 0.5);
    }
    50% {
      box-shadow: 0 0 0 6px rgba(255, 145, 0, 0);
    }
  }

  .form-switch .form-check-input {
    width: 3rem;
    height: 1.5rem;
    cursor: pointer;
  }

  .form-switch .form-check-input:checked {
    background-color: #667eea;
    border-color: #667eea;
  }

  .btn-save {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .btn-save:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    color: white;
  }

  .btn-save:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .btn-restart {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .btn-restart:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(245, 87, 108, 0.4);
    color: white;
  }

  .btn-restart:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  @media (max-width: 768px) {
    .nav-tabs .nav-link {
      padding: 0.75rem 0.75rem;
      font-size: 0.9rem;
    }
  }
</style>
{{ template "page/head_end" .}}

{{ template "page/body_start" .}}
{{ template "component/sidebar" . }}

<div class="main-content">
  <!-- Top Navbar -->
  <nav class="navbar-top">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h4 class="mb-0"><i class="bi bi-gear-fill me-2"></i>{{ i18n "menu.settings" }}</h4>
        <small class="text-muted">{{ i18n "pages.settings.manage" }}</small>
      </div>
    </div>
  </nav>

  <div class="container-fluid px-4">
    <!-- Loading State -->
    <div id="loadingState" class="text-center py-5">
      <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;"></div>
      <p class="mt-3 text-muted">{{ i18n "loading" }}...</p>
    </div>

    <!-- Main Content -->
    <div id="mainContent" style="display: none;">
      <!-- Security Alerts -->
      <div id="securityAlerts" class="mb-3" style="display: none;">
        <div class="alert alert-security">
          <h5 class="mb-2"><i class="bi bi-exclamation-triangle-fill me-2"></i>{{ i18n "secAlertTitle" }}</h5>
          <p class="mb-2"><strong>{{ i18n "secAlertConf" }}</strong></p>
          <ul id="alertsList" class="mb-0"></ul>
        </div>
      </div>

      <!-- Save Bar -->
      <div class="save-bar">
        <div class="d-flex justify-content-between align-items-center flex-wrap px-3">
          <div class="d-flex gap-2 mb-2 mb-md-0">
            <button class="btn btn-save" id="saveBtn" disabled>
              <i class="bi bi-check-circle me-1"></i> {{ i18n "pages.settings.save" }}
            </button>
            <button class="btn btn-restart" id="restartBtn" disabled>
              <i class="bi bi-arrow-clockwise me-1"></i> {{ i18n "pages.settings.restartPanel" }}
            </button>
          </div>
          <div class="alert alert-warning mb-0" style="padding: 0.5rem 1rem;">
            <i class="bi bi-info-circle me-1"></i> {{ i18n "pages.settings.infoDesc" }}
          </div>
        </div>
      </div>

      <!-- Tabs -->
      <ul class="nav nav-tabs mb-4" id="settingsTabs" role="tablist">
        <li class="nav-item" role="presentation">
          <button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel" type="button">
            <i class="bi bi-gear-wide-connected me-1"></i> {{ i18n "pages.settings.panelSettings" }}
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="security-tab" data-bs-toggle="tab" data-bs-target="#security" type="button">
            <i class="bi bi-shield-lock me-1"></i> {{ i18n "pages.settings.securitySettings" }}
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="telegram-tab" data-bs-toggle="tab" data-bs-target="#telegram" type="button">
            <i class="bi bi-telegram me-1"></i> {{ i18n "pages.settings.TGBotSettings" }}
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link" id="subscription-tab" data-bs-toggle="tab" data-bs-target="#subscription" type="button">
            <i class="bi bi-cloud-arrow-down me-1"></i> {{ i18n "pages.settings.subSettings" }}
          </button>
        </li>
      </ul>

      <!-- Tab Content -->
      <div class="tab-content" id="settingsTabContent">
        <!-- Panel Settings Tab -->
        <div class="tab-pane fade show active" id="panel" role="tabpanel">
          <div class="accordion" id="panelAccordion">
            <!-- General Configs -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#generalConfigs">
                  {{ i18n "pages.xray.generalConfigs" }}
                </button>
              </h2>
              <div id="generalConfigs" class="accordion-collapse collapse show" data-bs-parent="#panelAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.panelListeningIP" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.panelListeningIPDesc" }}</div>
                    <input type="text" class="form-control" id="webListen">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.panelListeningDomain" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.panelListeningDomainDesc" }}</div>
                    <input type="text" class="form-control" id="webDomain">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.panelPort" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.panelPortDesc" }}</div>
                    <input type="number" class="form-control" id="webPort" min="1" max="65535">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.panelUrlPath" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.panelUrlPathDesc" }}</div>
                    <input type="text" class="form-control" id="webBasePath">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.sessionMaxAge" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.sessionMaxAgeDesc" }}</div>
                    <input type="number" class="form-control" id="sessionMaxAge" min="60">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.pageSize" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.pageSizeDesc" }}</div>
                    <input type="number" class="form-control" id="pageSize" min="0" step="5">
                  </div>
                </div>
              </div>
            </div>

            <!-- Notifications -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#notifications">
                  {{ i18n "pages.settings.notifications" }}
                </button>
              </h2>
              <div id="notifications" class="accordion-collapse collapse" data-bs-parent="#panelAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.expireTimeDiff" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.expireTimeDiffDesc" }}</div>
                    <input type="number" class="form-control" id="expireDiff" min="0">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.trafficDiff" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.trafficDiffDesc" }}</div>
                    <input type="number" class="form-control" id="trafficDiff" min="0">
                  </div>
                </div>
              </div>
            </div>

            <!-- Certificates -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#certificates">
                  {{ i18n "pages.settings.certs" }}
                </button>
              </h2>
              <div id="certificates" class="accordion-collapse collapse" data-bs-parent="#panelAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.publicKeyPath" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.publicKeyPathDesc" }}</div>
                    <input type="text" class="form-control" id="webCertFile">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.privateKeyPath" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.privateKeyPathDesc" }}</div>
                    <input type="text" class="form-control" id="webKeyFile">
                  </div>
                </div>
              </div>
            </div>

            <!-- Date and Time -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#datetime">
                  {{ i18n "pages.settings.dateAndTime" }}
                </button>
              </h2>
              <div id="datetime" class="accordion-collapse collapse" data-bs-parent="#panelAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.timeZone" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.timeZoneDesc" }}</div>
                    <input type="text" class="form-control" id="timeLocation">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Security Settings Tab -->
        <div class="tab-pane fade" id="security" role="tabpanel">
          <div class="accordion" id="securityAccordion">
            <!-- Admin Account -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#adminAccount">
                  {{ i18n "pages.settings.security.admin" }}
                </button>
              </h2>
              <div id="adminAccount" class="accordion-collapse collapse show" data-bs-parent="#securityAccordion">
                <div class="accordion-body">
                  <form id="userForm">
                    <div class="setting-item">
                      <div class="setting-label">{{ i18n "pages.settings.oldUsername" }}</div>
                      <input type="text" class="form-control" id="oldUsername" autocomplete="username">
                    </div>
                    <div class="setting-item">
                      <div class="setting-label">{{ i18n "pages.settings.currentPassword" }}</div>
                      <input type="password" class="form-control" id="oldPassword" autocomplete="current-password">
                    </div>
                    <div class="setting-item">
                      <div class="setting-label">{{ i18n "pages.settings.newUsername" }}</div>
                      <input type="text" class="form-control" id="newUsername">
                    </div>
                    <div class="setting-item">
                      <div class="setting-label">{{ i18n "pages.settings.newPassword" }}</div>
                      <input type="password" class="form-control" id="newPassword" autocomplete="new-password">
                    </div>
                    <div class="mt-3">
                      <button type="button" class="btn btn-primary" id="updateUserBtn">
                        <i class="bi bi-check-circle me-1"></i> {{ i18n "confirm" }}
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </div>

            <!-- Two-Factor Authentication -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#twoFactor">
                  {{ i18n "pages.settings.security.twoFactor" }}
                </button>
              </h2>
              <div id="twoFactor" class="accordion-collapse collapse" data-bs-parent="#securityAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.security.twoFactorEnable" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.security.twoFactorEnableDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="twoFactorEnable">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Telegram Bot Settings Tab -->
        <div class="tab-pane fade" id="telegram" role="tabpanel">
          <div class="accordion" id="telegramAccordion">
            <!-- General Configs -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#tgGeneral">
                  {{ i18n "pages.xray.generalConfigs" }}
                </button>
              </h2>
              <div id="tgGeneral" class="accordion-collapse collapse show" data-bs-parent="#telegramAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.telegramBotEnable" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.telegramBotEnableDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="tgBotEnable">
                    </div>
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.telegramToken" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.telegramTokenDesc" }}</div>
                    <input type="text" class="form-control" id="tgBotToken">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.telegramChatId" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.telegramChatIdDesc" }}</div>
                    <input type="text" class="form-control" id="tgBotChatId">
                  </div>
                </div>
              </div>
            </div>

            <!-- Telegram Notifications -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#tgNotifications">
                  {{ i18n "pages.settings.notifications" }}
                </button>
              </h2>
              <div id="tgNotifications" class="accordion-collapse collapse" data-bs-parent="#telegramAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.telegramNotifyTime" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.telegramNotifyTimeDesc" }}</div>
                    <input type="text" class="form-control" id="tgRunTime">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.tgNotifyBackup" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.tgNotifyBackupDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="tgBotBackup">
                    </div>
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.tgNotifyLogin" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.tgNotifyLoginDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="tgBotLoginNotify">
                    </div>
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.tgNotifyCpu" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.tgNotifyCpuDesc" }}</div>
                    <input type="number" class="form-control" id="tgCpu" min="0" max="100">
                  </div>
                </div>
              </div>
            </div>

            <!-- Proxy and Server -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#tgProxy">
                  {{ i18n "pages.settings.proxyAndServer" }}
                </button>
              </h2>
              <div id="tgProxy" class="accordion-collapse collapse" data-bs-parent="#telegramAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.telegramProxy" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.telegramProxyDesc" }}</div>
                    <input type="text" class="form-control" id="tgBotProxy" placeholder="socks5://user:pass@host:port">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.telegramAPIServer" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.telegramAPIServerDesc" }}</div>
                    <input type="text" class="form-control" id="tgBotAPIServer" placeholder="https://api.example.com">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Subscription Settings Tab -->
        <div class="tab-pane fade" id="subscription" role="tabpanel">
          <div class="accordion" id="subscriptionAccordion">
            <!-- General Configs -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#subGeneral">
                  {{ i18n "pages.xray.generalConfigs" }}
                </button>
              </h2>
              <div id="subGeneral" class="accordion-collapse collapse show" data-bs-parent="#subscriptionAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subEnable" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subEnableDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="subEnable">
                    </div>
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subTitle" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subTitleDesc" }}</div>
                    <input type="text" class="form-control" id="subTitle">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subListen" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subListenDesc" }}</div>
                    <input type="text" class="form-control" id="subListen">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subDomain" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subDomainDesc" }}</div>
                    <input type="text" class="form-control" id="subDomain">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subPort" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subPortDesc" }}</div>
                    <input type="number" class="form-control" id="subPort" min="1" max="65535">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subPath" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subPathDesc" }}</div>
                    <input type="text" class="form-control" id="subPath">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subURI" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subURIDesc" }}</div>
                    <input type="text" class="form-control" id="subURI" placeholder="(http|https)://domain[:port]/path/">
                  </div>
                </div>
              </div>
            </div>

            <!-- Information -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#subInfo">
                  {{ i18n "pages.settings.information" }}
                </button>
              </h2>
              <div id="subInfo" class="accordion-collapse collapse" data-bs-parent="#subscriptionAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subEncrypt" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subEncryptDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="subEncrypt">
                    </div>
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subShowInfo" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subShowInfoDesc" }}</div>
                    <div class="form-check form-switch">
                      <input class="form-check-input" type="checkbox" id="subShowInfo">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Certificates -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#subCerts">
                  {{ i18n "pages.settings.certs" }}
                </button>
              </h2>
              <div id="subCerts" class="accordion-collapse collapse" data-bs-parent="#subscriptionAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subCertPath" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subCertPathDesc" }}</div>
                    <input type="text" class="form-control" id="subCertFile">
                  </div>
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subKeyPath" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subKeyPathDesc" }}</div>
                    <input type="text" class="form-control" id="subKeyFile">
                  </div>
                </div>
              </div>
            </div>

            <!-- Update Intervals -->
            <div class="accordion-item mb-3">
              <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#subIntervals">
                  {{ i18n "pages.settings.intervals" }}
                </button>
              </h2>
              <div id="subIntervals" class="accordion-collapse collapse" data-bs-parent="#subscriptionAccordion">
                <div class="accordion-body">
                  <div class="setting-item">
                    <div class="setting-label">{{ i18n "pages.settings.subUpdates" }}</div>
                    <div class="setting-description">{{ i18n "pages.settings.subUpdatesDesc" }}</div>
                    <input type="number" class="form-control" id="subUpdates" min="1">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

{{template "page/body_scripts" .}}
<script>
let oldSettings = {};
let currentSettings = {};

$(document).ready(function() {
  loadSettings();

  $('#saveBtn').on('click', saveSettings);
  $('#restartBtn').on('click', restartPanel);
  $('#updateUserBtn').on('click', updateUser);

  // Watch for changes
  setInterval(checkForChanges, 1000);

  // Bind all input fields to track changes
  $('input, select, textarea').on('input change', markAsModified);
});

function loadSettings() {
  $('#loadingState').show();
  $('#mainContent').hide();

  axios.post('/panel/setting/all')
    .then(response => {
      if (response.data.success) {
        const settings = response.data.obj;
        oldSettings = JSON.parse(JSON.stringify(settings));
        currentSettings = JSON.parse(JSON.stringify(settings));

        populateSettings(settings);
        checkSecurityAlerts(settings);

        $('#loadingState').hide();
        $('#mainContent').fadeIn();
      }
    })
    .catch(error => {
      console.error('Failed to load settings:', error);
    });
}

function populateSettings(settings) {
  // Panel settings
  $('#webListen').val(settings.webListen || '');
  $('#webDomain').val(settings.webDomain || '');
  $('#webPort').val(settings.webPort || 54321);
  $('#webBasePath').val(settings.webBasePath || '/');
  $('#sessionMaxAge').val(settings.sessionMaxAge || 3600);
  $('#pageSize').val(settings.pageSize || 50);
  $('#expireDiff').val(settings.expireDiff || 0);
  $('#trafficDiff').val(settings.trafficDiff || 0);
  $('#webCertFile').val(settings.webCertFile || '');
  $('#webKeyFile').val(settings.webKeyFile || '');
  $('#timeLocation').val(settings.timeLocation || 'Asia/Shanghai');

  // Security settings
  $('#twoFactorEnable').prop('checked', settings.twoFactorEnable || false);

  // Telegram settings
  $('#tgBotEnable').prop('checked', settings.tgBotEnable || false);
  $('#tgBotToken').val(settings.tgBotToken || '');
  $('#tgBotChatId').val(settings.tgBotChatId || '');
  $('#tgRunTime').val(settings.tgRunTime || '@daily');
  $('#tgBotBackup').prop('checked', settings.tgBotBackup || false);
  $('#tgBotLoginNotify').prop('checked', settings.tgBotLoginNotify || false);
  $('#tgCpu').val(settings.tgCpu || 0);
  $('#tgBotProxy').val(settings.tgBotProxy || '');
  $('#tgBotAPIServer').val(settings.tgBotAPIServer || '');

  // Subscription settings
  $('#subEnable').prop('checked', settings.subEnable || false);
  $('#subTitle').val(settings.subTitle || '');
  $('#subListen').val(settings.subListen || '');
  $('#subDomain').val(settings.subDomain || '');
  $('#subPort').val(settings.subPort || 0);
  $('#subPath').val(settings.subPath || '/sub/');
  $('#subURI').val(settings.subURI || '');
  $('#subEncrypt').prop('checked', settings.subEncrypt || false);
  $('#subShowInfo').prop('checked', settings.subShowInfo || false);
  $('#subCertFile').val(settings.subCertFile || '');
  $('#subKeyFile').val(settings.subKeyFile || '');
  $('#subUpdates').val(settings.subUpdates || 24);
}

function gatherSettings() {
  return {
    // Panel settings
    webListen: $('#webListen').val(),
    webDomain: $('#webDomain').val(),
    webPort: parseInt($('#webPort').val()),
    webBasePath: $('#webBasePath').val(),
    sessionMaxAge: parseInt($('#sessionMaxAge').val()),
    pageSize: parseInt($('#pageSize').val()),
    expireDiff: parseInt($('#expireDiff').val()),
    trafficDiff: parseInt($('#trafficDiff').val()),
    webCertFile: $('#webCertFile').val(),
    webKeyFile: $('#webKeyFile').val(),
    timeLocation: $('#timeLocation').val(),

    // Security settings
    twoFactorEnable: $('#twoFactorEnable').is(':checked'),
    twoFactorToken: currentSettings.twoFactorToken || '',

    // Telegram settings
    tgBotEnable: $('#tgBotEnable').is(':checked'),
    tgBotToken: $('#tgBotToken').val(),
    tgBotChatId: $('#tgBotChatId').val(),
    tgLang: currentSettings.tgLang || 'en-US',
    tgRunTime: $('#tgRunTime').val(),
    tgBotBackup: $('#tgBotBackup').is(':checked'),
    tgBotLoginNotify: $('#tgBotLoginNotify').is(':checked'),
    tgCpu: parseInt($('#tgCpu').val()),
    tgBotProxy: $('#tgBotProxy').val(),
    tgBotAPIServer: $('#tgBotAPIServer').val(),

    // Subscription settings
    subEnable: $('#subEnable').is(':checked'),
    subTitle: $('#subTitle').val(),
    subListen: $('#subListen').val(),
    subDomain: $('#subDomain').val(),
    subPort: parseInt($('#subPort').val()),
    subPath: $('#subPath').val(),
    subURI: $('#subURI').val(),
    subEncrypt: $('#subEncrypt').is(':checked'),
    subShowInfo: $('#subShowInfo').is(':checked'),
    subCertFile: $('#subCertFile').val(),
    subKeyFile: $('#subKeyFile').val(),
    subUpdates: parseInt($('#subUpdates').val())
  };
}

function markAsModified() {
  currentSettings = gatherSettings();
}

function checkForChanges() {
  const hasChanges = JSON.stringify(oldSettings) !== JSON.stringify(currentSettings);
  $('#saveBtn').prop('disabled', !hasChanges);
  $('#restartBtn').prop('disabled', hasChanges);
}

function saveSettings() {
  const settings = gatherSettings();

  showLoading();
  axios.post('/panel/setting/update', settings)
    .then(response => {
      hideLoading();
      if (response.data.success) {
        showNotification('{{ i18n "success" }}', 'success');
        oldSettings = JSON.parse(JSON.stringify(settings));
        currentSettings = JSON.parse(JSON.stringify(settings));
      }
    })
    .catch(error => {
      hideLoading();
      console.error('Failed to save settings:', error);
    });
}

function restartPanel() {
  if (!confirm('{{ i18n "pages.settings.restartPanelDesc" }}')) return;

  showLoading();
  axios.post('/panel/setting/restartPanel')
    .then(response => {
      if (response.data.success) {
        showNotification('{{ i18n "pages.settings.restartPanelSuccess" }}', 'success');

        // Wait 5 seconds then redirect
        setTimeout(() => {
          const isTLS = currentSettings.webCertFile !== '' || currentSettings.webKeyFile !== '';
          const protocol = isTLS ? 'https:' : 'http:';
          const host = currentSettings.webDomain || window.location.hostname;
          const port = currentSettings.webPort;
          const base = currentSettings.webBasePath || '/';

          window.location.href = `${protocol}//${host}:${port}${base}panel/settings`;
        }, 5000);
      }
    })
    .catch(error => {
      hideLoading();
      console.error('Failed to restart panel:', error);
    });
}

function updateUser() {
  const userData = {
    oldUsername: $('#oldUsername').val().trim(),
    oldPassword: $('#oldPassword').val().trim(),
    newUsername: $('#newUsername').val().trim(),
    newPassword: $('#newPassword').val().trim()
  };

  if (!userData.oldUsername || !userData.oldPassword) {
    showNotification('{{ i18n "pages.login.toasts.emptyUsernameOrPassword" }}', 'warning');
    return;
  }

  showLoading();
  axios.post('/panel/setting/updateUser', userData)
    .then(response => {
      hideLoading();
      if (response.data.success) {
        showNotification('{{ i18n "success" }}', 'success');
        setTimeout(() => {
          window.location.href = basePath + 'logout';
        }, 1000);
      }
    })
    .catch(error => {
      hideLoading();
      console.error('Failed to update user:', error);
    });
}

function checkSecurityAlerts(settings) {
  const alerts = [];

  if (window.location.protocol !== 'https:') {
    alerts.push('{{ i18n "secAlertSSL" }}');
  }

  if (settings.webPort == 54321) {
    alerts.push('{{ i18n "secAlertPanelPort" }}');
  }

  const panelPath = window.location.pathname.split('/').length < 4;
  if (panelPath && settings.webBasePath == '/') {
    alerts.push('{{ i18n "secAlertPanelURI" }}');
  }

  if (settings.subEnable) {
    const subPath = settings.subURI.length > 0 ? new URL(settings.subURI).pathname : settings.subPath;
    if (subPath == '/sub/') {
      alerts.push('{{ i18n "secAlertSubURI" }}');
    }
  }

  if (alerts.length > 0) {
    const alertsList = $('#alertsList');
    alertsList.empty();
    alerts.forEach(alert => {
      alertsList.append(`<li>${alert}</li>`);
    });
    $('#securityAlerts').show();
  } else {
    $('#securityAlerts').hide();
  }
}
</script>
{{ template "page/body_end" .}}
